package com.csscis.ssm.core.util;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * Created by qinghe on 2016/3/29.
 */
public class Sender {

    public static void sendMsg(){
        try {
            //创建发送方的套接字，IP默认为本地，端口号随机
            DatagramSocket sendSocket = new DatagramSocket();

            //由于数据报的数据是以字符数组传的形式存储的，所以传转数据
            byte[] buf={0x30 ,0x00 ,0x00 ,0x00  ,0x04 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00  ,0x01 ,0x00 ,0x00 ,0x00
                    ,0x01 ,0x01 ,0x01 ,0x01  , (byte) 0xe9,0x03 ,0x00 ,0x00  ,
                    0x31 ,0x39 ,0x32 ,0x2E  ,0x31 ,0x36 ,0x38 ,0x2E,0x34 ,0x37 ,0x2E ,0x33  ,0x38 ,0x3A ,0x38 ,0x30  ,0x30 ,0x30 ,
                    0x00 ,0x00  ,0x10 ,0x00 ,0x00 ,0x00
            };
            //确定发送方的IP地址及端口号，地址为本地机器地址
            int port = 19999;
            InetAddress ip = InetAddress.getLocalHost();
            //创建发送类型的数据报：
            DatagramPacket sendPacket = new DatagramPacket(buf,buf.length,InetAddress.getByName("10.44.48.202"),port);
            //通过套接字发送数据：
            sendSocket.send(sendPacket);
            sendSocket.setSoTimeout(1000);//设置receive超时异常，否则一直阻塞在这里
            //确定接受反馈数据的缓冲存储器，即存储数据的字节数组
            byte[] getBuf = new byte[1024];
            //创建接受类型的数据报
            DatagramPacket getPacket = new DatagramPacket(getBuf,getBuf.length);
            //通过套接字接受数据
            sendSocket.receive(getPacket);
            //解析反馈的消息，并打印
            String backMes = new String(getBuf,0,getPacket.getLength());
            System.out.println("接受方返回的消息："+backMes);
            //关闭套接字
            sendSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
